package 华为OD机试B卷复用题.进阶题;

import utils.MyUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class HJ21_信道分配 {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner in = new Scanner(new File("src/main/java/华为OD机试B卷复用题/进阶题/input/21.txt"));
        MyUtil.START();
        //        Solution(in);
        Solution2(in);
        MyUtil.END();
    }

    static int res = 0, N = 0;
    // 方法一：从最大的信道开始累加，满足了 res 就 +1，同时减去使用的信道，直到没法再满足。每次取最大，有浪费的可能性
    static void Solution(Scanner in) {
        // 初始化变量
        N = in.nextInt();
        int[] volumns = new int[N + 1];
        for (int i = 0; i <= N; i++) {
            volumns[i] = (int) Math.pow(2, i);
        }
        int[] nums = new int[N + 1];
        for (int i = 0; i <= N; i++) {
            nums[i] = in.nextInt();
        }
        int Message = in.nextInt();
        // 开始处理
        boolean handleResult = true;
        while (handleResult) {
            handleResult = handle(volumns, nums, Message);
        }
        System.out.println(res);
    }

    static boolean handle(int[] volumns, int[] nums, int target) {
        int tmp = target;
        for (int i = N; i >= 0; i--) {
            int volumn = volumns[i];
            for (int j = 1; j <= nums[i]; j++) {
                tmp -= volumn;
                if (tmp <= 0) {
                    nums[i] -= j;
                    res++;
                    return true;
                }
            }
            if (tmp > 0) {
                nums[i] = 0;
            }
        }
        return false;
    }

    // 方法二：把所有信道加入集合中，其它和方法一一样，都有浪费的风险
    static void Solution2(Scanner in) {
        // 初始化变量
        N = in.nextInt();
        List<Integer> list = new ArrayList<>(); // 把所有信道都放到同一个集合中，已然有序
        for (int i = 0; i <= N; i++) {
            int volumn = (int) Math.pow(2, i);
            int num = in.nextInt();
            for (int j = 0; j < num; j++) {
                list.add(volumn);
            }
        }
        int Message = in.nextInt();
        for (int i = list.size() - 1; i >= 0; i--) {
            if (list.get(i) >= Message) {
                res++;
                list.remove(i);
            }
        }
        int tmp = Message;
        while (list.size() > 0) {
            for (int i = list.size() - 1; i >= 0; i--) {
                tmp -= list.get(i);
                list.remove(i);
                if (tmp <= 0) {
                    res++;
                    tmp = Message;
                }
            }
        }
        System.out.println(res);
    }
}
